package org.cheetah.spring.xml.factory;

import java.util.List;
import java.util.Map;

import org.cheetah.Service;
import org.cheetah.activities.Activity;
import org.cheetah.util.FastHashtable;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.AbstractFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ServiceFactoryBean extends AbstractFactoryBean<Service> implements
		ApplicationContextAware {

	private Map<String, Object> vars;

	private List<?> activities;

	private ApplicationContext springContext;

	public void setVars(Map<String, Object> vars) {
		this.vars = vars;
	}

	public void setActivities(List<?> activities) {
		this.activities = activities;
	}

	public Class<?> getObjectType() {
		return Service.class;
	}

	public void setApplicationContext(ApplicationContext springctx)
			throws BeansException {
		this.springContext = springctx;
	}

	protected Service createInstance() throws Exception {
		Service instance = new Service();

		// set pipeline
		instance.setActivities(activities.toArray(new Activity[0]));

		// set additional context variables
		if (springContext != null) {
			int count = vars == null ? 0 : vars.size();

			FastHashtable<String, Object> vars = new FastHashtable<String, Object>(
					1 + count);

			if (count > 0) {
				vars.putAll(this.vars);
			}
			vars.put("springContext", springContext);

			instance.setVars(vars);
		}

		// initialize!
		instance.init();

		return instance;
	}
}
